//
//  PhonePwdCodeLoginViewModel.swift
//  User
//
//  Created by ET|冰琳 on 2017/1/12.
//  Copyright © 2017年 IB. All rights reserved.
//

import Foundation
import ReactiveSwift
import ReactiveCocoa

open class PhonePwdCodeLoginViewModel<Service: PhonePwdCodeLoginService>: NSObject {
    
    open var phone = MutableProperty<String?>(nil)
    open var code  = MutableProperty<String?>(nil)
    open var password = MutableProperty<String?>(nil)
    
    open var phoneValide = MutableProperty(false)
    open var codeValide = MutableProperty(false)
    open var passwordValide = MutableProperty(false)
    
    open var phoneValidor: Validator?
    open var codeValidor: Validator?
    open var passwordValidor: Validator?
    
    
    open var getCode: Action<(), Service.PhonePwdCodeResult, NSError>!
    open var login:   Action<(), Service.PhonePwdLoginResult, NSError>!
    
    
    private var service: Service
    
    public init(service: Service) {
        self.service = service
        super.init()
        self.bind()
    }
    
    private func bind() {
        
        phoneValide <~ phone.signal.map{
            let validator = self.phoneValidor ?? PhoneValidator()
            return validator.validate(txt: $0)
        }
        
        codeValide <~ code.signal.map{
            let validator = self.codeValidor ?? DefaultValidator()
            return validator.validate(txt: $0)
        }
        
        passwordValide <~ code.signal.map{
            let validator = self.passwordValidor ?? DefaultValidator()
            return validator.validate(txt: $0)
        }
        
        getCode = Action { _ in
            return self.service.getLoginVerifyCode(phone: self.phone.value)
        }
        
        login = Action {
            return self.service.loginWith(phone: self.phone.value,
                                          code: self.code.value,
                                          password: self.password.value)
        }
    }
}
